﻿using System;
using System.Data;
using System.Threading;
using System.Windows.Forms;
using ChinaDynastyTours.Controls;
using ChinaDynastyTours.Models;

namespace ChinaDynastyTours.Views
{
    public partial class EntertainmenOrderForm : DevExpress.XtraEditors.XtraForm
    {
        //输入参数
        public string _TourGroupID { get; set; }//团ID
        public string _LocalPlanScheduleDate { get; set; }//团状态
        public string _LocalPlanScheduleID { get; set; }//行程计划ID
        public string _TourGroupScheduleID { get; set; }//大程计划ID

        public int _AdultNum { get; set; }
        public int _ChildNum { get; set; }
        //public int _AccompanyNum { get; set; }
        
        //输出三处
        public string _returnRestaurant { get; set; }//返回选择的餐厅内容

        public DataTable _dtOrderData;

        public string _CiceroniName { get; set; }
        public string _CiceroniPhone { get; set; }
        
        public EntertainmenOrderForm(int SelectedPageIndex)
        {
            InitializeComponent();
        }

        private void TabControlOrders_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            LoadSelectedPageGridViewData();
        }
        
        private void EntertainmenRestaurantOrderForm_Load(object sender, EventArgs e)
        {
            LoadSelectedPageGridViewData();
        
        }

        private void LoadSelectedPageGridViewData()
        {
            int isSignedPark = btnIsSignedPark.EditValue.ToString() == "签约" ? 1 : 0;
            int isSignedPlay = btnIsSignedPlay.EditValue.ToString() == "签约" ? 1 : 0;
            switch (TabControlOrders.SelectedTabPageIndex)
            {
                case 0://景点门票
                    parkProviderGridControl.DataSource = ServiceInfoCtrl.GetParkTicketServiceData(isSignedPark);
                     break;
                case 1://演出门票
                     playTicketGridControl.DataSource = ServiceInfoCtrl.GetPlayTicketServiceData(isSignedPlay);
                     break;
                default:
                    break;
            }
            LoadOrderGridPageData();
        }

        private void LoadOrderGridPageData()
        {
            orderGridControl.DataSource = _dtOrderData = EntertainmenRestaurantOrderCtrl.GetEntertainmentOrderData(_TourGroupID, _LocalPlanScheduleID);
            _dtOrderData.ColumnChanged += new DataColumnChangeEventHandler(OrderData_ColumnChanged);
        }

        #region 修改预订信息后的自动保存

        void OrderData_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            int providerId = int.Parse(e.Row["ProviderID"].ToString());
            string providerName = e.Row["ProviderName"].ToString();
            string serverName = e.Row["ServiceName"].ToString();

            EntertainmenRestaurantOrderEntity entertainmentOrder = new EntertainmenRestaurantOrderEntity();

            entertainmentOrder.EntertainmentOrderID = int.Parse(e.Row["EntertainmentOrderID"].ToString());/*重点字段*/

            entertainmentOrder.ServiceDate = DateTime.Parse(e.Row["ServiceDate"].ToString()).ToString("yyyy-MM-dd");
            entertainmentOrder.ProviderID = providerId;
            entertainmentOrder.ProviderName = providerName;
            entertainmentOrder.ServiceName = serverName;
            entertainmentOrder.AccompanyNum = int.Parse(e.Row["AccompanyNum"].ToString());
            entertainmentOrder.AdultNum = int.Parse(e.Row["AdultNum"].ToString());
            entertainmentOrder.ChildNum = int.Parse(e.Row["ChildNum"].ToString());
            entertainmentOrder.AdultUnitPrice = decimal.Parse(e.Row["AdultUnitPrice"].ToString());
            entertainmentOrder.ChildUnitPrice = decimal.Parse(e.Row["ChildUnitPrice"].ToString());
            entertainmentOrder.AccompanyUnitPrice = decimal.Parse(e.Row["AccompanyUnitPrice"].ToString());
            entertainmentOrder.OthersCost = decimal.Parse(e.Row["OthersCost"].ToString());
            entertainmentOrder.CiceroniName = e.Row["CiceroniName"].ToString();
            entertainmentOrder.CiceroniPhone = e.Row["CiceroniPhone"].ToString();
            entertainmentOrder.Remark = e.Row["Remark"].ToString();

            ExpenseEntity expense = new ExpenseEntity()
            {
                /*这里只有Budget在界面中是可被修改的内容，其余全部用原值更新*/
                ExpenseID = int.Parse(e.Row["ExpenseID"].ToString()), /*重点字段*/
                ProviderID = providerId,
                ProviderName = providerName,
                ServiceName = serverName,

                Budget = decimal.Parse(e.Row["AdultUnitPrice"].ToString()) * int.Parse(e.Row["AdultNum"].ToString()) + decimal.Parse(e.Row["OthersCost"].ToString()),
                TourgroupID = e.Row["TourgroupID"].ToString(),
                TourgroupName=e.Row["TourgroupName"].ToString(),
                //TourGroupScheduleID = int.Parse(_TourGroupScheduleID),
                Remark = e.Row["Remark"].ToString(),
                Status = e.Row["Status"].ToString(),
                TypeBelong = e.Row["TypeBelong"].ToString(),
            };

            EntertainmenRestaurantOrderCtrl.UpdateEntertainmenRestaurantOrderData(expense, entertainmentOrder);

            //更新团审核成本
            TeamGroupCtrl.UpdateTourGroupBudgeCost(_TourGroupID);
            //刷新数据
            LoadOrderGridPageData();
        }
        #endregion
        
        private void CreateEntertainmentOrderData(DevExpress.XtraGrid.Views.Grid.GridView gridView,DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            decimal adultUnitPrice = 0;
            decimal accompanyUnitPrice = 0;
            string serverName = "";
            int providerId = 0;
            string providerName = "";
            string contractPath = "";
            string typeBelong = ProviderTypeEnum.景点.ToString();//初始化为娱乐

            DateTime OffSeason; 
            DateTime BusySeason;

            DateTime serviceDate;

            
            switch (gridView.Name)
            {
                case "parkProviderGridView":
                    serviceDate = DateTime.Parse(_LocalPlanScheduleDate);
                    string serviceYear = serviceDate.Year.ToString();
                    OffSeason = DateTime.Parse(SysParameterCtrl.GetValueForKey("OffSeasonStart") + "-" + serviceYear);
                    BusySeason = DateTime.Parse(SysParameterCtrl.GetValueForKey("BusySeasonStart") + "-" + serviceYear);


                    if (serviceDate > OffSeason || serviceDate < BusySeason)  //根据淡旺季时间获取价格
                        adultUnitPrice = decimal.Parse(parkProviderGridView.GetRowCellValue(e.RowHandle, "OffSeasonPrice").ToString());
                    else
                        adultUnitPrice = decimal.Parse(parkProviderGridView.GetRowCellValue(e.RowHandle, "BusySeasonPrice").ToString());

                    serverName = parkProviderGridView.GetRowCellValue(e.RowHandle, "ServiceName").ToString();
                    providerId = int.Parse(parkProviderGridView.GetRowCellValue(e.RowHandle, "ProviderID").ToString());
                    providerName = parkProviderGridView.GetRowCellValue(e.RowHandle, "ProviderName").ToString();
                    contractPath = parkProviderGridView.GetRowCellValue(e.RowHandle, "ContractPath").ToString();
                    accompanyUnitPrice = 0;
                    typeBelong = ProviderTypeEnum.景点.ToString();
                    break;
                case "playTicketGridView":
                    adultUnitPrice = decimal.Parse(playTicketGridView.GetRowCellValue(e.RowHandle, "Price").ToString());
                    serverName = playTicketGridView.GetRowCellValue(e.RowHandle, "ServiceName").ToString();
                    providerId = int.Parse(playTicketGridView.GetRowCellValue(e.RowHandle, "ProviderID").ToString());
                    providerName = playTicketGridView.GetRowCellValue(e.RowHandle, "ProviderName").ToString();
                    contractPath = playTicketGridView.GetRowCellValue(e.RowHandle, "ContractPath").ToString();
                    accompanyUnitPrice = 0;
                    typeBelong = ProviderTypeEnum.演出.ToString();
                    break;
                default:
                    break;
            }

            //获得导游信息
            //DataTable dtGuide = GuideArrangeCtrl.GetGuideInfoForPrint(_TourGroupID);

            //创建娱乐预定信息内容
            EntertainmenRestaurantOrderEntity entertainmentOrder = new EntertainmenRestaurantOrderEntity();
            entertainmentOrder.OrderState = OrderStateEnum.未订.ToString();/*重点内容，初始化订单状态为‘未定’*/
            entertainmentOrder.TourgroupID = _TourGroupID;
            entertainmentOrder.TourgroupName = TeamGroupCtrl.GetTeamGroupNameById(_TourGroupID);
            
            entertainmentOrder.ProviderID =providerId;
            entertainmentOrder.ProviderName = providerName;
            entertainmentOrder.ServiceName = serverName;
            entertainmentOrder.ContractPath = contractPath;

            entertainmentOrder.LocalPlanScheduleID = int.Parse(_LocalPlanScheduleID);
            entertainmentOrder.ServiceDate = DateTime.Parse(_LocalPlanScheduleDate).ToString("yyyy-MM-dd");
            entertainmentOrder.AdultUnitPrice = adultUnitPrice;
            entertainmentOrder.AccompanyUnitPrice = accompanyUnitPrice;
            entertainmentOrder.AccompanyNum = 0;
            entertainmentOrder.AdultNum = _AdultNum;
            entertainmentOrder.ChildNum = _ChildNum;
            entertainmentOrder.ChildUnitPrice = 0;
            entertainmentOrder.OthersCost = 0;
            entertainmentOrder.CiceroniName = _CiceroniName;//dtGuide.Rows.Count > 0 ? dtGuide.Rows[0]["CiceroniName"].ToString() : _CiceroniName;
            entertainmentOrder.CiceroniPhone = _CiceroniPhone;//dtGuide.Rows.Count > 0 ? dtGuide.Rows[0]["Phone"].ToString() : _CiceroniPhone;
            entertainmentOrder.Remark = "";

            //创建费用
            ExpenseEntity expense = new ExpenseEntity()
            {
                //ExpenseID = _ExpenseID,
                TourgroupID = _TourGroupID,
                TourgroupName = TeamGroupCtrl.GetTeamGroupNameById(_TourGroupID),
                TourGroupScheduleID = int.Parse(_TourGroupScheduleID),
                ProviderID = providerId,
                ProviderName = providerName,
                ServiceName = serverName,
                Budget = adultUnitPrice * _AdultNum,
                PayTotal = 0,
                ApplyPayTotal = 0,
                AdjustAmount = 0,
                Status = ExpenseStatusEnum.计划.ToString(),
                TypeBelong = typeBelong,
                ApplyPay = 0,
                PayStatus = PayApplyStatusEnum.未付.ToString(),
                CreateByUserName = Thread.CurrentPrincipal.Identity.Name, //UserInfoCtrl.GetNameByUserName(Thread.CurrentPrincipal.Identity.Name)
                CreateTime=DateTime.Now.ToString("yyyy-MM-dd"),
                ExpenseTypeID = 5,//所属费用类型(费用类型表中存储着编号，此编号是固定的，1房费、2团费、3餐费、4交通费、5门票、6杂费)
                ExpenseType = BaseInfoCtrl.GetExpenseTypeNameByID(5)//同上
          };
            EntertainmenRestaurantOrderCtrl.CreateEntertainmenRestaurantOrderAndExpenseData(expense, entertainmentOrder);

            //更新团审核成本
            TeamGroupCtrl.UpdateTourGroupBudgeCost(_TourGroupID);
        }


        private void ProviderGridView_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if (e.Clicks == 2)
            {
                CreateEntertainmentOrderData(sender as DevExpress.XtraGrid.Views.Grid.GridView, e);
            }
            //刷新数据
            LoadOrderGridPageData();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            //模拟parkProviderGridView的行双击事件
            switch (TabControlOrders.SelectedTabPageIndex)
	        {
                case 0:
                    ProviderGridView_RowClick(parkProviderGridView, new DevExpress.XtraGrid.Views.Grid.RowClickEventArgs(new DevExpress.Utils.DXMouseEventArgs(MouseButtons.Left, 2, 0, 0, 0), parkProviderGridView.FocusedRowHandle));
                    break;
                case 1:
                    ProviderGridView_RowClick(playTicketGridView, new DevExpress.XtraGrid.Views.Grid.RowClickEventArgs(new DevExpress.Utils.DXMouseEventArgs(MouseButtons.Left, 2, 0, 0, 0), playTicketGridView.FocusedRowHandle));
                    break;
                default:
                 break;
	        }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (orderGridView.GetRowCellValue(orderGridView.FocusedRowHandle, "Status").ToString() != ExpenseStatusEnum.计划.ToString()
                || orderGridView.GetRowCellValue(orderGridView.FocusedRowHandle, "PayStatus").ToString() != PayApplyStatusEnum.未付.ToString()
                || orderGridView.GetRowCellValue(orderGridView.FocusedRowHandle, "WipeOffMethod").ToString() == WipeOffMethodEnum.签单报账.ToString()
                || orderGridView.GetRowCellValue(orderGridView.FocusedRowHandle, "OrderState").ToString() != OrderStateEnum.未订.ToString())
            {
                MessageBox.Show("该预订已生效，不能删除！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            EntertainmenRestaurantOrderCtrl.DeleteEntertainmenRestaurantOrder(orderGridView.GetRowCellValue(orderGridView.FocusedRowHandle, "EntertainmentOrderID").ToString(),
                orderGridView.GetRowCellValue(orderGridView.FocusedRowHandle, "ExpenseID").ToString());
            //刷新数据
            LoadOrderGridPageData();
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            if ((orderGridView.GetRowCellValue(orderGridView.FocusedRowHandle, "Status").ToString() != ExpenseStatusEnum.计划.ToString()
             && orderGridView.GetRowCellValue(orderGridView.FocusedRowHandle, "Status").ToString() != ExpenseStatusEnum.导游报销.ToString())
             || orderGridView.GetRowCellValue(orderGridView.FocusedRowHandle, "PayStatus").ToString() != PayApplyStatusEnum.未付.ToString())

            {
                MessageBox.Show("该预订已支付或提交审核，不能取消！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (MessageBox.Show("确定取消选中的预订信息吗？", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                string expenseId = orderGridView.GetRowCellValue(orderGridView.FocusedRowHandle, "ExpenseID").ToString();
                string entertainmentOrderID = orderGridView.GetRowCellValue(orderGridView.FocusedRowHandle, "EntertainmentOrderID").ToString();

                ExpensesCtrl.UpdateExpenseStatusData(expenseId, ExpenseStatusEnum.取消);
                EntertainmenRestaurantOrderCtrl.UpdateEntertainmenRestauranOrderStateData(entertainmentOrderID, OrderStateEnum.取消);

                //更新团审核成本
                TeamGroupCtrl.UpdateTourGroupBudgeCost(_TourGroupID);

                //刷新
                orderGridView.SetRowCellValue(orderGridView.FocusedRowHandle, "Status", ExpenseStatusEnum.取消);
                orderGridView.SetRowCellValue(orderGridView.FocusedRowHandle, "OrderState", OrderStateEnum.取消);
            }

        }

        #region 关闭窗口保存数据
        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void EntertainmenRestaurantOrderForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //激发团数据更新,转移一下焦点即可
            btnExit.Focus();
        } 
        #endregion

       
    }
}
